import 'dart:async';
import 'dart:math';

import 'package:flutter/material.dart';

class AnimatedBar extends StatefulWidget {
  final double width;
  final double maxHeight;
  final Color color;

  const AnimatedBar({
    super.key,
    required this.width,
    required this.maxHeight,
    required this.color,
  });

  @override
  State<AnimatedBar> createState() => _AnimatedBarState();
}

class _AnimatedBarState extends State<AnimatedBar> {
  late double height;
  final _random = Random();
  Timer? _timer;
  final _precomputedHeights = <double>[];

  @override
  void initState() {
    super.initState();
    height = widget.maxHeight * _random.nextDouble();
    _precomputeHeights();
    _startOptimizedAnimation();
  }

  void _precomputeHeights() {
    for (int i = 0; i < 20; i++) {
      _precomputedHeights.add(
        widget.maxHeight * (0.3 + _random.nextDouble() * 0.7),
      );
    }
  }

  void _startOptimizedAnimation() {
    var index = 0;
    _timer = Timer.periodic(
      const Duration(milliseconds: 150), // 固定150ms间隔
      (_) {
        if (!mounted) return;
        setState(() {
          height = _precomputedHeights[index % _precomputedHeights.length];
          index++;
        });
      },
    );
  }

  @override
  void dispose() {
    _timer?.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return AnimatedContainer(
      duration: const Duration(milliseconds: 100), // 缩短动画时间
      curve: Curves.linear, // 使用线性曲线
      width: widget.width,
      height: height,
      decoration: BoxDecoration(
        color: widget.color,
        borderRadius: BorderRadius.circular(2),
      ),
    );
  }
}
